<template>
  <div class="card" style="width: 60%; padding: 30px; margin: auto">
    <h3 style="text-align: center; margin-bottom: 20px">企业管理员信息</h3>

    <el-form ref="formRef" :model="Admin.form" :rules="Admin.rules" label-width="120px">

      <!-- 账号 -->
      <el-form-item label="账号">
        <el-input v-model="Admin.form.username" disabled />
      </el-form-item>

      <!-- 公司名称 -->
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="Admin.form.companyName" placeholder="请输入公司名称" :disabled="!isEditing" />
      </el-form-item>
<!-- 公司描述 -->
<el-form-item label="公司描述" prop="companyDescription">
  <el-input v-model="Admin.form.companyDescription" type="textarea" :rows="3" placeholder="请输入公司描述" :disabled="!isEditing" />
</el-form-item>


      <!-- 性别 -->
      <el-form-item label="性别" prop="sex">
        <el-select v-model="Admin.form.sex" placeholder="请选择性别" :disabled="!isEditing">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="Admin.form.email" placeholder="请输入邮箱" :disabled="!isEditing" />
      </el-form-item>

      <!-- 电话 -->
      <el-form-item label="电话" prop="telephone">
        <el-input v-model="Admin.form.telephone" placeholder="请输入电话" :disabled="!isEditing" />
      </el-form-item>

      <!-- 工作城市 -->
      <!-- 所在城市（支持多选） -->
      <el-form-item label="工作城市" prop="city">
        <el-select v-model="User.form.cityList" multiple placeholder="请选择城市" :disabled="!isEditing">
          <el-option
            v-for="item in cityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
<!-- 薪资 -->
<el-form-item label="薪资" prop="salary">
  <el-input-number v-model="Admin.form.salary" :min="0" :max="100000" placeholder="请输入薪资" :disabled="!isEditing" />
</el-form-item>

      <!-- 福利待遇 -->
      <el-form-item label="福利待遇" prop="benefits">
        <el-input v-model="Admin.form.benefits" type="textarea" :rows="3" placeholder="请输入福利待遇" :disabled="!isEditing" />
      </el-form-item>

      <!-- 上下班时间 -->
      <el-form-item label="上下班时间" prop="officeHours">
        <el-time-picker
          v-model="Admin.form.startTime"
          value-format="HH:mm"
          format="HH:mm"
          placeholder="开始时间"
          :disabled="!isEditing"
        />
        <span style="margin: 0 10px">至</span>
        <el-time-picker
          v-model="Admin.form.endTime"
          value-format="HH:mm"
          format="HH:mm"
          placeholder="结束时间"
          :disabled="!isEditing"
        />
      </el-form-item>
      <!-- 职位 -->
<el-form-item label="职位" prop="jobTitle">
  <el-input v-model="Admin.form.jobTitle" placeholder="请输入职位名称" :disabled="!isEditing" />
</el-form-item>
<!-- 职位要求 -->
<el-form-item label="职位要求" prop="jobRequirements">
  <el-input v-model="Admin.form.jobRequirements" type="textarea" :rows="3" placeholder="请输入职位要求" :disabled="!isEditing" />
</el-form-item>
<!-- 招聘人数 -->
<el-form-item label="招聘人数" prop="jobHiringCount">
  <el-input-number v-model="Admin.form.jobHiringCount" :min="0" :max="1000" placeholder="请输入招聘人数" :disabled="!isEditing" />
</el-form-item>

      <!-- 注册时间 -->
      <el-form-item label="注册时间">
        <el-input v-model="Admin.form.registerTime" disabled />
      </el-form-item>

      <!-- 最后更新时间 -->
      <el-form-item label="最后更新时间">
        <el-input v-model="Admin.form.updateTime" disabled />
      </el-form-item>

      <!-- 按钮区域 -->
      <el-form-item style="text-align: center">
        <el-button @click="toggleEdit" type="primary" v-if="!isEditing">修改信息</el-button>
        <el-button @click="updateAdmin" type="success" v-else>提交信息</el-button>
        <el-button @click="router.back()" plain>返回</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { parseJwt, getToken } from '@/utils/auth'

const formRef = ref()
const cityOptions = [
  { label: '北京', value: '北京' },
  { label: '上海', value: '上海' },
  { label: '天津', value: '天津' },
  { label: '重庆', value: '重庆' },
  { label: '河北', value: '河北' },
  { label: '山西', value: '山西' },
  { label: '辽宁', value: '辽宁' },
  { label: '吉林', value: '吉林' },
  { label: '黑龙江', value: '黑龙江' },
  { label: '江苏', value: '江苏' },
  { label: '浙江', value: '浙江' },
  { label: '安徽', value: '安徽' },
  { label: '福建', value: '福建' },
  { label: '江西', value: '江西' },
  { label: '山东', value: '山东' },
  { label: '河南', value: '河南' },
  { label: '湖北', value: '湖北' },
  { label: '湖南', value: '湖南' },
  { label: '广东', value: '广东' },
  { label: '海南', value: '海南' },
  { label: '四川', value: '四川' },
  { label: '贵州', value: '贵州' },
  { label: '云南', value: '云南' },
  { label: '陕西', value: '陕西' },
  { label: '甘肃', value: '甘肃' },
  { label: '青海', value: '青海' },
  { label: '台湾', value: '台湾' },
  { label: '内蒙古', value: '内蒙古' },
  { label: '广西', value: '广西' },
  { label: '西藏', value: '西藏' },
  { label: '宁夏', value: '宁夏' },
  { label: '新疆', value: '新疆' },
  { label: '香港', value: '香港' },
  { label: '澳门', value: '澳门' }
];
// 企业管理员信息（默认只读）
const Admin = reactive({
  form: {
    username: '',
    companyName: '',
    sex: '',
    email: '',
    telephone: '',
    cityList: [],
    benefits: '',
    startTime: '', // 上班时间
    endTime: '',   // 下班时间
    registerTime: '',
    updateTime: '',
    jobTitle: '', // 新增：职位
    jobRequirements: '', // 新增：职位要求
    jobHiringCount: null, // 新增：招聘人数
    companyDescription: '', // 新增：公司描述
    salary: null // 新增：薪资
  },
  rules: {
    companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
    ],
    telephone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
    
    benefits: [{ required: true, message: '请输入福利待遇', trigger: 'blur' }],
    jobTitle: [{ required: true, message: '请输入职位名称', trigger: 'blur' }], // 新增：职位校验规则
    jobRequirements: [{ required: true, message: '请输入职位要求', trigger: 'blur' }], // 新增：职位要求校验规则
    jobHiringCount: [{ required: true, message: '请输入招聘人数', trigger: 'blur' }], // 新增：招聘人数校验规则
    companyDescription: [{ required: true, message: '请输入公司描述', trigger: 'blur' }], // 新增：公司描述校验规则
    salary: [{ required: true, message: '请输入薪资', trigger: 'blur' }] // 新增：薪资校验规则
  }
})

const isEditing = ref(false)
// 模拟从 JWT 解析用户信息并加载数据
const loadAdminInfo = () => {
  const token = getToken()
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }

  const userInfo = parseJwt(token)
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  // 获取企业管理员详情（调用后端接口）
axios.get(`/api/company/info/${userInfo.id}`, {
  headers: {
    Authorization: 'Bearer ' + token
  }
}).then(res => {
  if (res.data.code === 200 && res.data.data) {
    const admin = res.data.data
    Admin.form.username = admin.username
    Admin.form.companyName = admin.companyName
    Admin.form.sex = admin.sex
    Admin.form.email = admin.email
    Admin.form.telephone = admin.telephone
    Admin.form.cityList = admin.city ? admin.city.split(',') : []
    Admin.form.benefits = admin.benefits

    // officeHours 格式为 "09:00 - 18:00"
    const officeHours = admin.officeHours?.split(' - ')
    Admin.form.startTime = officeHours?.[0] || ''
    Admin.form.endTime = officeHours?.[1] || ''

    Admin.form.registerTime = formatDate(admin.registerTime)
    Admin.form.updateTime = formatDate(admin.updateTime)

    // 新增字段赋值
    Admin.form.jobTitle = admin.jobTitle
    Admin.form.jobRequirements = admin.jobRequirements
    Admin.form.jobHiringCount = admin.jobHiringCount
    Admin.form.companyDescription = admin.companyDescription
    Admin.form.salary = admin.salary
  } else {
    ElMessage.error('获取用户信息失败')
  }
  }).catch(err => {
    console.error('请求失败:', err)
    ElMessage.error('网络异常，请重试')
  })
}

// 格式化日期函数
const formatDate = (dateStr) => {
  if (dateStr == null) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 更新企业管理员信息
const updateAdmin = async () => {
  const userInfo = parseJwt()
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  const dataToSend = {
  id: userInfo.id,
  companyName: Admin.form.companyName,
  sex: Admin.form.sex,
  email: Admin.form.email,
  telephone: Admin.form.telephone,
  city: Admin.form.cityList.join(','), // 合并城市列表为字符串
  benefits: Admin.form.benefits,
  officeHours: `${Admin.form.startTime} - ${Admin.form.endTime}`,
  jobTitle: Admin.form.jobTitle,
  jobRequirements: Admin.form.jobRequirements,
  jobHiringCount: Admin.form.jobHiringCount,
  companyDescription: Admin.form.companyDescription, // 新增：公司描述
  salary: Admin.form.salary // 新增：薪资
}


  try {
    const res = await axios.put('/api/company/update', dataToSend, {
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      localStorage.setItem('admin', JSON.stringify(Admin.form))
      toggleEdit() // 返回只读模式
    } else {
      ElMessage.error(res.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('请求错误:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录状态异常，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('网络异常，请重试')
    }
  }
}

onMounted(() => {
  loadAdminInfo()
})
</script>
